package com.ckcool.api.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Author: <a href="1006319834@qq.com">王冰卿</a>
 * @Description:
 * @Version: 1.0
 * @Date: Created in 2023/3/15 16:25
 * @Modified By:
 */
public class AesUtil {

	private static final Logger logger = LoggerFactory.getLogger(AesUtil.class);

	private AesUtil() {
	}

	private static final String ECB_MODE = "AES/ECB/PKCS5PADDING";

	/**
	 * <p>
	 * aes加密采用ecb模式，填充方式为pkcs5padding
	 * 其中cbc模式需要有向量iv
	 * </p>
	 *
	 * @param password 密码
	 * @param appKey   生成的16位appKey
	 * @return aes加密的密码
	 */
	public static String encryptEcb(String password, String appKey) {
		try {
			SecretKeySpec spec = new SecretKeySpec(appKey.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance(ECB_MODE);
			cipher.init(Cipher.ENCRYPT_MODE, spec);
			byte[] encrypted = cipher.doFinal(password.getBytes());
			return Base64.encodeBase64String(encrypted);
		} catch (Exception ex) {
			logger.error("encrypt ecb error.", ex);
		}
		return "";
	}

}
